<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Mobile_Member_module extends CI_Module
{
    public $data;
    public $sid ;
    public $open_id ;
    public function __construct(){
        parent::__construct();
        $this->load->model('member.User_model');

        $this->load->model('expert.Expert_model');
        $this->load->model('admin.Adminuser_model');
        $this->load->model('weixin.weixin_model');
        $this->load->model('order.Orderinfo_model');
        $this->load->model('admin.Upload_model');
        $this->sid = $GLOBALS['sid'];
        $this->data =$GLOBALS['config'];
        $this->setting = $this->weixin_model->db_get_setting();
        define('TOKEN',     @$this->setting['token']);
        define('APPID',     @$this->setting['appid']);


    }


    public function complete_info()
    {
        $this->load->view(MOBILE_TEMPLATE_NAME.'/complete_info', $this->data);
    }


    public function verify_mobile($mobile,$action)
    {
        if(!($this->User_model->_check_is_mobile($mobile)))
        {
            return json_encode(array('status'=>'0','info' => '手机号不合法'));
        }
        if($action=='exist')
        {
            $mobile_info =  $this->User_model->_mobile_exist($mobile);
        }
        if($action=='repeat')
        {
            $mobile_info =  $this->User_model->_mobile_ver($mobile);
        }
        if($mobile_info['status']=='0') return $mobile_info;
        return true ;
    }





    public function center()
    {

        $user_id = $this->session->userdata('user_id');
        $this->session->set_userdata('redirect_uri',site_url('mobile/member/center'));
        if(!$user_id) redirect('mobile/oauth/oauth');

        if(!empty($user_id))
        {
            $this->data['info'] = $this->User_model->_user_info($user_id);
            $this->data['identity'] = '1';
        }


        $this->data['account'] = ($this->data['info']['mobile']) ? ($this->data['info']['mobile']) : '';

        $this->data['common'] = array(
            array(
                'head'   => '个人中心',
                'nav'   => 'center',
                'title'   => '个人中心',
                'keywords' => @$this->data['info']['profile'] ? $this->data['info']['profile'] : '暂无简介',
                'description' => @$this->data['info']['profile'] ? $this->data['info']['profile'] : '暂无简介',
                'noshare'    => '1'
            )
        );


        $this->load->view(MOBILE_TEMPLATE_NAME.'/center', $this->data);
    }

    public function card()
    {
        if($_GET['eid']){
            $user_id = intval($_GET['eid']) ;
        }

        if(!$user_id){
            redirect('mobile/index');
        }

        if($_GET['incr']){
            $this->Expert_model->db_update_views_share($user_id, 0, 1);
            exit('succeed');
        }

        $this->data['info'] = $this->Expert_model->_expert_info($user_id);
        $this->data['account'] = $this->data['info']['mobile'] ;

        $this->data['wechat'] = $this->weixin_model->db_get_setting();

        $this->data['admin_user_id'] = $user_id;

        $this->load->helper('cookie');

        $ctrip_allianceid = $this->data['ctrip_allianceid'];
        $ctrip_sid = $this->data['ctrip_sid'];
       

        $mobile = $this->data['info']['mobile'] ? $this->data['info']['mobile'] : $this->data['site_service_phone'];
        $expert_company = $this->data['info']['expert_company'] ? $this->data['info']['expert_company'] : $this->data['company'];

        set_cookie('from_card', $user_id, 3153600000);
        set_cookie('from_tel', $mobile, 315360000);
        set_cookie('card_info', serialize($this->data['info']), 3153600000);
        set_cookie('expert_company', $expert_company, 3153600000);

        $_COOKIE['from_card'] = $user_id;
        $_COOKIE['from_tel'] = $mobile;
        $_COOKIE['expert_company'] = $expert_company;
        $_COOKIE['card_info'] = serialize($this->data['info']);
        $this->data['company'] = $expert_company;
        $title = $this->data['company'] . $this->data['info']['realname'];
        $keywords = $this->data['info']['profile'] ? $this->data['info']['profile'] : '暂无简介';
        $description = $this->data['info']['profile'] ? $this->data['info']['profile'] : '暂无简介';
        $imgurl = URLPIC.$this->data['info']['avatar'];

        $this->data['common'] = array(
            array(
                'title'   => $title,
                'keywords' => $keywords,
                'description' =>$description,
                'noback' => true
            )
        );


        //---------------------------------------------------------
        if($this->data['depart_citys']){
            $this->data['depart_citys_list'] = $this->area_model->get_area_name(array($this->data['depart_citys']),false);
            $this->data['depart_citys_list'][SITECITY] = SITECITYNAME;
        }

        $this->data['city_id'] = CURRENT_CITY_ID;;
        $city_name = $this->area_model->get_area_name(array($this->data['city_id']));
        $this->data['city_name'] = str_replace(array('[',']'),array('',''),$city_name);

        $this->data['site_logo'] = $GLOBALS['config']['sitelogo'];
        $this->data['company'] = $expert_company ? $expert_company : $GLOBALS['config']['company'];

        //---------------------------------------------------------


        $this->setting = $this->weixin_model->db_get_setting();

        $appid = $this->setting['appid'];
        $appsecret = $this->setting['appsecret'];
        $geturl = get_url();
        $noncestr = uniqid('wx');
        $timestamp = time();
        $signature = __get_signature($appid, $appsecret, $noncestr, $geturl, $timestamp);

        if(DEBUG){
            $debug = 'true';
        }else{
            $debug = 'false';
        }
        $incrurl = site_url('mobile/member/card/?eid='.$user_id.'&incr=1');
        $sharehtml = <<<HTML
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
var title='$title', desc='$description', link='$geturl',imgUrl='$imgurl';
wx.config({
    debug:$debug,
    appId: '$appid',
    timestamp: $timestamp,
    nonceStr: '$noncestr',
    signature: '$signature',
    jsApiList: [
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo'
    ]
});
function todoaftershare() {
  $.get('$incrurl', function(){
  });
}
wx.ready(function () {
    wx.onMenuShareAppMessage({title: title,desc: desc,link: link,imgUrl: imgUrl,success:function(){    todoaftershare();}});
    wx.onMenuShareTimeline({title: title,link: link,imgUrl: imgUrl,success:function(){    todoaftershare();}  });
    wx.onMenuShareQQ({title: title,desc: desc,link: link,imgUrl: imgUrl,success:function(){    todoaftershare();}   });
    wx.onMenuShareWeibo({title: title,desc: desc,link: link,imgUrl: imgUrl,success:function(){    todoaftershare();}   });
});
</script>
HTML;
        $this->data['sharehtml'] = $sharehtml;

        $this->Expert_model->db_update_views_share($user_id, 1);
        $this->data['wechat']['weixincardtpl'] = trim($this->data['wechat']['weixincardtpl']);
        /*
        if($this->data['wechat']['weixincardtpl'] && $this->data['wechat']['weixincardtpl'] != 'default'){

            $this->load->view('weixincard/'.$this->data['wechat']['weixincardtpl'].'/index',$this->data);
        } else {
            $this->load->view(MOBILE_TEMPLATE_NAME.'/weixin_card',$this->data);
        }
         */
        if(!$this->data['wechat']['weixincardtpl']){
            $this->data['wechat']['weixincardtpl'] = 'default';
        }
        $this->load->view('weixincard/'.$this->data['wechat']['weixincardtpl'].'/index',$this->data);

//        if(MOBILE_TEMPLATE_NAME=='weixin'/* && $this->data['wechat']['weixincardtpl'] == 'colorful'*/) { //去除模版限制
//            $this->load->view(MOBILE_TEMPLATE_NAME.'/weixin_card',$this->data);
//        }
//        else{
//
//            if (MOBILE_TEMPLATE_NAME =='default' && !in_array(SITEID, array(129,32936))) {
//                $this->data['wechat']['weixincardtpl'] = 'touch';
//            }
//            $this->load->view('weixincard/'.$this->data['wechat']['weixincardtpl'].'/index',$this->data);
//        }
    }

    public function card_body(){

        $this->data['ads_line']  = $this->Line_model->get_list(9,1,"c.expand_1=1 and c.sid = $this->sid");
        $this->data['ctrip_flight'] = 'http://u.ctrip.com/union/CtripRedirect.aspx?TypeID=615&sid=441804&allianceid=17065&ouid=' ;
        $this->data['ctrip_hotel'] = 'http://u.ctrip.com/union/CtripRedirect.aspx?TypeID=636&sid=441804&allianceid=17065&ouid=' ;
        $ctrip_allianceid = '17065' ;
        $ctrip_sid = '450577' ;
        $ctrip_allianceid = $this->data['ctrip_allianceid'];
        $ctrip_sid = $this->data['ctrip_sid'];
        if(!empty($ctrip_allianceid)&&!empty($ctrip_sid))
        {
            $this->data['ctrip_flight'] = 'http://u.ctrip.com/union/CtripRedirect.aspx?TypeID=615&sid='.$ctrip_sid.'&allianceid='.$ctrip_allianceid.'&ouid=' ;
            $this->data['ctrip_hotel'] = 'http://u.ctrip.com/union/CtripRedirect.aspx?TypeID=636&sid='.$ctrip_sid.'&allianceid='.$ctrip_allianceid.'&ouid=' ;
        }
        $city = $this->data['sitecityname'];
        $this->data['common'] = array(
            array(
                'noback' => TRUE,
                'head'   => $this->data['sitename'],
                'title'   => SITECITYNAME.'旅游网_'.SITECITYNAME.'旅游攻略',
                'keywords'   => SITECITYNAME.'旅游网',
                'description'   => SITECITYNAME.'旅游网-为您提供'.SITECITYNAME.'旅游资讯、'.SITECITYNAME.'旅游攻略、'.SITECITYNAME.'旅游线路，包括'.SITECITYNAME.'热门景区介绍、精彩游记、旅游地图、交通出行、游玩路线、旅游优惠信息、住宿、饮食、购物等旅游信息的综合性旅游门户网站。'
            )
        );

        $this->load->view(MOBILE_TEMPLATE_NAME.'/weixin_card_body',$this->data);
    }

    public function profile()
    {
        @$user_id = $this->session->userdata('user_id');
        @$admin_user_id = $this->session->userdata('admin_user_id');
        if($user_id||$admin_user_id) $check_login = TRUE;
        if(!$check_login) redirect(site_url('mobile/member/login'));
        if(!empty($user_id))
        {
            $this->data['info'] = $this->User_model->_user_info($user_id);
            $this->data['identity'] = '1';
            $this->data['form_url'] = site_url('mobile/member/edit_member');
        }
        if(!empty($admin_user_id))
        {
            $this->data['info'] = $this->Expert_model->_expert_info($admin_user_id);
            $this->data['identity'] = '2';
            $this->data['form_url'] = site_url('mobile/member/edit_expert');
        }
        if(!empty($this->data['info']['nickname']))  $this->data['name'] = $this->data['info']['nickname'] ;
        if(!empty($this->data['info']['username']))  $this->data['name'] = $this->data['info']['username'] ;
        $this->data['common'] = array(
            array(
                'head'   => '个人详细资料',
                'title'   => '个人详细资料',
                'nav'   => 'center',
                'noshare'    => '1'
            )
        );
        $this->load->view(MOBILE_TEMPLATE_NAME.'/'.'profile', $this->data);
    }

    public function edit_complete_member()
    {
        $mobile = $this->input->post('mobile');
        $realname = $this->input->post('realname');

        @$user_id = $this->session->userdata('user_id');
        $where = array('user_id'=>$user_id);

        if(!empty($mobile))
        {
            $res = $this->User_model->_edit_member(array('mobile'=>$mobile),$where) ;
        }
        if(!empty($realname)){
            $res = $this->User_model->_edit_member_expand(array('realname'=>$realname),$where) ;
        }
        if($res)  return json_encode(array('status'=>'1','info' => '已完善'));
        return json_encode(array('status'=>'0','info' => '完善失败'));
    }

    public function edit_member()
    {
       
        $username = $this->input->post('name');
        $gender = $this->input->post('gender');
        $mobile = $this->input->post('mobile');
        $realname = $this->input->post('realname');
        $address = $this->input->post('address');
        $verify = $this->User_model->_username_ver($username,$this->session->userdata('user_id'));
        if($verify['status']=='0') return json_encode($verify);
        @$user_id = $this->session->userdata('user_id');
        $where = array('user_id'=>$user_id);
        $base_data['username'] = $username;
        $base_data['mobile'] = $mobile;
        $base_data['gender'] = $gender;
        if(!empty($base_data))
        {
            $res = $this->User_model->_edit_member(array('username'=>$username,'mobile'=>$mobile,'address'=>$address),$where) ;
            $res = $this->User_model->_edit_member_expand(array('gender'=>$gender,'realname'=>$realname),$where) ;

        }
        if($res)  return json_encode(array('status'=>'1','info' => '修改成功'));
        return json_encode(array('status'=>'0','info' => '修改失败'));
    }

    public function edit_expert()
    {
        @$admin_user_id = $this->session->userdata('admin_user_id');
        $where = array('id'=>$admin_user_id);
        $nickname = $this->input->post('name');
        $gender = $this->input->post('gender');
        $array['nickname'] = $nickname ;
        $array['gender'] = $gender ;
        $res = $this->Expert_model->_edit_expert($array,$where) ;
        if($res)  return json_encode(array('status'=>'1','info' => '修改成功'));
        return json_encode(array('status'=>'0','info' => '修改失败'));
    }


    /**
     * 收藏列表
     */

    public function favourite_list()
    {
        $check_login = FALSE;
        @$user_id = $this->session->userdata('user_id');
        @$admin_user_id = $this->session->userdata('admin_user_id');
        if($user_id||$admin_user_id) $check_login = TRUE;
        if(!$check_login) redirect(site_url('mobile/member/login?referer='.$_GET['referer']));
        $pagesize = 20;
        $type = $this->input->get('type') ;
        $page = !empty($_GET['page']) && $_GET['page']>0 ? intval($_GET['page']) : '1';
        $type = !empty($type)? $type:'1';
        $isajax = $this->input->get('isajax');
        if($type=='1')
        {
            $where = array('user_id'=>$user_id,'type'=>'1');
            $template = 'favourite_line_list';
        }
        if($type=='2'){
            $where = array('user_id'=>$user_id,'type'=>'2');
            $template = 'favourite_ticket_list';
        }
        if($type=='3')
        {
            $where = array('user_id'=>$user_id,'type'=>'3');
            $template = 'favourite_rent_list';
        }
        $this->data['datalist'] = $this->User_model->get_favourite_list($where, $pagesize, $page);
        $this->data['line_url'] = site_url('mobile/member/favourite_list?type=1');
        $this->data['ticket_url'] = site_url('mobile/member/favourite_list?type=2');
        $this->data['rent_url'] = site_url('mobile/member/favourite_list?type=3');
        $this->data['page'] = $page;
        $this->data['common'] = array(array('head' => '我的收藏', 'noshare'    => '1'));


        if ($type == '1') // 线路
        {
            if (!empty($this->data['datalist'])) {
                foreach ($this->data['datalist'] as $k => $v) {

                    $this->data['datalist'][$k]['link'] = site_url('mobile/line/profile?id=' . $v['favourite_id']);
                }
            }
            $this->data['index_url'] = site_url('mobile/member/favourite_list?type=1');
        }

        if ($type == '2')// 门票
        {
            if (!empty($this->data['datalist'])) {
                foreach ($this->data['datalist'] as $k => $v) {
                    $this->data['datalist'][$k]['link'] = site_url('mobile/scenery/profile/?id=' . $v['favourite_id']);
                }
            }
            $this->data['index_url'] = site_url('mobile/member/favourite_list?type=2');
        }

        if ($type == '3')// 租车
        {
            if (!empty($this->data['datalist'])) {
                foreach ($this->data['datalist'] as $k => $v) {
                    $this->data['datalist'][$k]['link'] = site_url('mobile/rent/profile/?id='.$v['favourite_id']);
                }
            }
            $this->data['index_url'] = site_url('mobile/member/favourite_list?type=2');
        }

        if ($isajax) {
            header('Content-type:application/json;charset=utf-8');
            echo json_encode($this->data['datalist']);
            exit;
        }

            $this->load->view(MOBILE_TEMPLATE_NAME.'/'.$template,$this->data);
        }


    /**
     * 收藏列表
     */

    public function add_favourite()
    {
        @$user_id = $this->session->userdata('user_id');
        $fav_id = $this->input->get_post('id');
        $type = $this->input->get_post('type');
        $title= $this->input->get_post('title');
        $cover = $this->input->get_post('cover');
        $check_return = $this->User_model->get_favourite_row(array('sid'=>$GLOBALS['sid'],'type'=>$type,'user_id'=>$user_id,'favourite_id'=>$fav_id));
        if($check_return)
        {
            echo json_encode(array('status'=>'0','msg'=>'已收藏，不可多次收藏'));
            exit;
        }

        if($type=='1'){
            $result = $this->Line_model->get_line_row(array('line_id'=>$fav_id),'line_thumb');
            if($result) $cover = $result['line_thumb'];
        }

        if($type=='2'){
            $result   = $this->scenic_model->scenic_by_id($fav_id);
            if($result) $cover = $result['file_url'];
        }



        $data = array(
            'sid'=>$this->sid,
            'user_id'=>$user_id,
            'type'=>$type,
            'favourite_id'=>$fav_id,
            'title'=>$title,
            'cover'=>$cover,
            'crts'=>time()
        );

        $return = array('status'=>'0','msg'=>'收藏失败');
        if($this->User_model->_add_favourite($data)){

            $return = array('status'=>'1','msg'=>'收藏成功');
        }
        echo json_encode($return);
    }

    /**
     * 收藏列表
     */

    public function delete_favourite()
    {
        $fav_id = $this->input->get_post('id');
        $where = array('id'=>$fav_id);
        $return = array('status'=>'0','msg'=>'删除失败');
        if($this->User_model->_delete_favourite($where)){

            $return = array('status'=>'1','msg'=>'删除成功');
        }
        echo json_encode($return);

    }

    public function upload_avatar()
    {
        $user_id = $this->input->get_post('uid');
        $config = $this->Upload_model->upload_config('avatar');
        $this->load->library('upload', $config);
        $absolute_path = str_replace('\\', '/', getcwd()) . '/';
        if (!$this->upload->do_upload('file')) {
            $error = array('error' => $this->upload->display_errors());
            $this->error($error['error'], '', true);
        } else {
            $data = array('upload_data' => $this->upload->data());
            $message = str_replace($absolute_path, '', $data['upload_data']['full_path']);
            $file_ext = $data['upload_data']['file_ext'];
            $dir_url = '/uploads/' . $GLOBALS['sid'] . '/avatar/';
            $des_url = $dir_url . $user_id . $file_ext;
            $des = getcwd() . $des_url;
            if (copy($message, $des)) {
                if (unlink($message)) {
                    $new_url = substr($des_url, 1);
                    $where = array('user_id' => $user_id);
                    $array['avatar'] = $new_url;
                    $res = $this->User_model->_edit_member_expand($array,$where);
                }
            }

            
           
            $this->success(URLPIC . $new_url.'?_='.time(), '', true);
        }
    }
}